/**
 * 快递单打印模板 - 编辑界面
 * 
 * @author 李静波
 */
Ext.define("PSI.Express.BillTemplateEditForm", {
	extend : "Ext.window.Window",

	config : {
		parentForm : null,
		entity : null
	},

	/**
	 * 初始化组件
	 */
	initComponent : function() {
		var me = this;
		var entity = me.getEntity();

		Ext.apply(me, {
					title : "编辑快递单打印模板",
					modal : true,
					onEsc : Ext.emptyFn,
					width : 700,
					height : 600,
					layout : "border",
					tbar : [{
								text : "保存",
								id : "buttonSave",
								iconCls : "PSI-button-ok",
								handler : me.onOK,
								scope : me
							}, "-", {
								text : "取消",
								id : "buttonCancel",
								iconCls : "PSI-button-cancel",
								handler : function() {
									PSI.MsgBox.confirm("请确认是否取消当前操作？",
											function() {
												me.close();
											});
								},
								scope : me
							}],
					items : [{
						region : "north",
						layout : {
							type : "table",
							columns : 2
						},
						height : 180,
						bodyPadding : 10,
						border : 0,
						items : [{
									xtype : "hidden",
									id : "companyId",
									name : "id",
									value : entity.get("id")
								}, {
									colspan : 2,
									border : 0,
									margin : 0,
									html : "<h2>" + entity.get("name")
											+ "</h2>"
								}, {
									id : "editPageTop",
									labelWidth : 100,
									labelAlign : "right",
									labelSeparator : "",
									xtype : "numberfield",
									hideTrigger : true,
									margin : 5,
									fieldLabel : "向下偏(毫米)"
								}, {
									id : "editPageLeft",
									labelWidth : 100,
									labelAlign : "right",
									labelSeparator : "",
									xtype : "numberfield",
									hideTrigger : true,
									margin : 5,
									fieldLabel : "向右偏(毫米)"
								}, {
									id : "editPageWidth",
									labelWidth : 100,
									labelAlign : "right",
									labelSeparator : "",
									xtype : "numberfield",
									hideTrigger : true,
									margin : 5,
									fieldLabel : "纸张宽度(毫米)"
								}, {
									id : "editPageHeight",
									labelWidth : 100,
									labelAlign : "right",
									labelSeparator : "",
									xtype : "numberfield",
									hideTrigger : true,
									margin : 5,
									fieldLabel : "纸张高度(毫米)"
								}, {
									id : "editPageOrient",
									xtype : "combo",
									queryMode : "local",
									editable : false,
									valueField : "id",
									labelWidth : 100,
									labelAlign : "right",
									labelSeparator : "",
									fieldLabel : "打印方向",
									margin : 5,
									store : Ext.create("Ext.data.ArrayStore", {
												fields : ["id", "text"],
												data : [["1", "纵向打印"],
														["2", "横向打印"]]
											}),
									value : 1
								}]
					}, {
						region : "center",
						layout : "fit",
						items : [me.getPageItemGrid()]

					}],
					listeners : {
						show : {
							fn : me.onWndShow,
							scope : me
						},
						close : {
							fn : me.onWndClose,
							scope : me
						}
					}
				});

		me.callParent(arguments);

		me.__editorList = ["editPageLeft", "editPageTop", "editPageWidth",
				"editPageHeight", "editPageOrient"];
	},

	onWindowBeforeUnload : function(e) {
		return (window.event.returnValue = e.returnValue = '确认离开当前页面？');
	},

	onWndClose : function() {
		Ext.get(window).un('beforeunload', this.onWindowBeforeUnload);
	},

	onWndShow : function() {
		Ext.get(window).on('beforeunload', this.onWindowBeforeUnload);

		var me = this;
		var el = me.getEl();
		var unitStore = me.unitStore;
		el.mask(PSI.Const.LOADING);

		var r = {
			url : PSI.Const.BASE_URL
					+ "Home/Express/getExpressBillTemplateInfo",
			params : {
				id : me.getEntity().get("id")
			},
			method : "POST",
			callback : function(options, success, response) {
				el.unmask();

				if (!success) {
					return;
				}

				var data = Ext.JSON.decode(response.responseText);

				var store = me.getPageItemGrid().getStore();
				store.removeAll();
				store.add(data.defaultItems);

				var sm = me.getPageItemGrid().getSelectionModel();
				if (data.hasData) {
					var v = data.pageInfo;
					Ext.getCmp("editPageLeft").setValue(v.pageLeft);
					Ext.getCmp("editPageTop").setValue(v.pageTop);
					Ext.getCmp("editPageWidth").setValue(v.pageWidth);
					Ext.getCmp("editPageHeight").setValue(v.pageHeight);
					Ext.getCmp("editPageOrient").setValue(v.pageOrient);

					var items = data.items;
					for (var i = 0; i < items.length; i++) {
						var item = items[i];
						var name = item.name;
						var index = store.findExact("name", name);
						if (index != -1) {
							sm.select(index, true);
						}
					}
				} else {
					var v = data.defaultPageValue;
					Ext.getCmp("editPageLeft").setValue(v.pageLeft);
					Ext.getCmp("editPageTop").setValue(v.pageTop);
					Ext.getCmp("editPageWidth").setValue(v.pageWidth);
					Ext.getCmp("editPageHeight").setValue(v.pageHeight);
					Ext.getCmp("editPageOrient").setValue(v.pageOrient);
				}

				me.initPrintCmp(data);
			}
		};

		Ext.Ajax.request(r);
	},

	onOK : function() {
		var me = this;

		var el = Ext.getBody();
		el.mask("正在保存中...");
		Ext.Ajax.request({
					url : PSI.Const.BASE_URL
							+ "Home/Express/editExpressBillTemplate",
					method : "POST",
					params : {
						jsonStr : me.getSaveData()
					},
					callback : function(options, success, response) {
						el.unmask();

						if (success) {
							var data = Ext.JSON.decode(response.responseText);
							if (data.success) {
								PSI.MsgBox.showInfo("成功保存数据", function() {
											me.close();
											me.getParentForm()
													.refreshTemplateInfo();
										});
							} else {
								PSI.MsgBox.showInfo(data.msg);
							}
						}
					}
				});
	},

	onEditSpecialKey : function(field, e) {
		if (e.getKey() === e.ENTER) {
			var me = this;
			var id = field.getId();
			for (var i = 0; i < me.__editorList.length; i++) {
				var editorId = me.__editorList[i];
				if (id === editorId) {
					var edit = Ext.getCmp(me.__editorList[i + 1]);
					edit.focus();
					edit.setValue(edit.getValue());
				}
			}
		}
	},

	getSaveData : function() {
		var me = this;

		var result = {
			companyId : Ext.getCmp("companyId").getValue(),
			pageLeft : Ext.getCmp("editPageLeft").getValue(),
			pageTop : Ext.getCmp("editPageTop").getValue(),
			pageWidth : Ext.getCmp("editPageWidth").getValue(),
			pageHeight : Ext.getCmp("editPageHeight").getValue(),
			pageOrient : Ext.getCmp("editPageOrient").getValue(),
			items : []
		};

		var sm = me.getPageItemGrid().getSelectionModel();
		var store = me.getPageItemGrid().getStore();
		for (var i = 0; i < store.getCount(); i++) {
			var item = store.getAt(i);
			result.items.push({
						selected : sm.isSelected(item),
						name : item.get("name"),
						caption : item.get("caption")
					});
		}

		return Ext.JSON.encode(result);
	},

	getPageItemGrid : function() {
		var me = this;
		if (me.__pageItemGrid) {
			return me.__pageItemGrid;
		}

		var modelName = "PSIExpressBillPageItem_EditForm";
		Ext.define(modelName, {
					extend : "Ext.data.Model",
					fields : ["id", "name", "caption"]
				});

		me.__pageItemGrid = Ext.create("Ext.grid.Panel", {
					selModel : {
						mode : "MULTI"
					},
					selType : "checkboxmodel",
					viewConfig : {
						enableTextSelection : true
					},
					columnLines : true,
					columns : [{
								xtype : "rownumberer"
							}, {
								header : "打印项",
								dataIndex : "caption",
								menuDisabled : true,
								sortable : false,
								flex : 1
							}],
					store : Ext.create("Ext.data.Store", {
								model : modelName,
								autoLoad : false,
								data : []
							}),
					listeners : {
						itemdblclick : {
							fn : me.onEditCompany,
							scope : me
						}
					}
				});

		return me.__pageItemGrid;
	}
});